import json
import ssl
import time

import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from geetest.geetest_v3 import GeeTest3
from undetected_chromedriver import Chrome, ChromeOptions

# 测试使用，请求https网站时，禁用SSL证书验证
ssl._create_default_https_context = ssl._create_unverified_context
# 创建ChromeOptions对象，并设置一些选项
options = ChromeOptions()
# 如果要使用无界面访问，开启此参数，默认有窗口界面
# options.add_argument('--headless')
# 将窗口最大化
options.add_argument('--start-maximized')
options.add_argument('--disable-infobars')
# 创建Chrome对象，并使用指定的选项启动Chrome浏览器
driver = Chrome(options=options)

import xlsxwriter as xw


def xw_toExcel(data, fileName):  # xlsxwriter库储存数据到excel
  workbook = xw.Workbook(fileName)  # 创建工作簿
  worksheet1 = workbook.add_worksheet("sheet1")  # 创建子表
  worksheet1.activate()  # 激活表
  title = ['序号', '申报事项', '主管部门', '兑现类型', '兑现金额', '兑现企业',
           '兑现时间']  # 设置表头
  worksheet1.write_row('A1', title)  # 从A1单元格开始写入表头
  i = 2  # 从第二行开始写入数据
  for j in range(len(data)):
    insertData = [data[j]["f1"], data[j]["f2"], data[j]["f3"], data[j]["f4"],
                  data[j]["f5"], data[j]["f6"], data[j]["f7"]]
    row = 'A' + str(i)
    worksheet1.write_row(row, insertData)
    i += 1
  workbook.close()  # 关闭表


def print_hi(name):
  # "-------------数据用例-------------"
  testData = [
  ]
  # Use a breakpoint in the code line below to debug your script.
  print(f'Hi, {name}')  #
  # 最大化
  driver.maximize_window()
  driver.get(
    'https://www.jxzwfww.gov.cn/jxzw/zwfwwPrefecturePage/hqt/view/dxgg/dxgg.html?flag=gj')
  # 修改页面属性
  # driver.execute_script("app.pageSize=500")
  # 给30秒时间操作
  time.sleep(20)
  # 1秒重新加载
  # time.sleep(1)

  while True:
    # 读取信息
    for e in driver.find_elements(By.CSS_SELECTOR, ".box_i"):
      testData.append({
        "f1": e.find_elements(By.CSS_SELECTOR, '.box_i_1')[0].text,
        "f2": e.find_elements(By.CSS_SELECTOR, '.box_i_1')[1].text,
        "f3": e.find_elements(By.CSS_SELECTOR, '.box_i_1')[2].text,
        "f4": e.find_elements(By.CSS_SELECTOR, '.box_i_1')[3].text,
        "f5": e.find_elements(By.CSS_SELECTOR, '.box_i_1')[4].text,
        "f6": e.find_elements(By.CSS_SELECTOR, '.box_i_1')[5].text,
        "f7": e.find_elements(By.CSS_SELECTOR, '.box_i_1')[6].text
      })
    # 切换下一页
    if (len(driver.find_elements(By.CSS_SELECTOR,
                                 '.ant-pagination-disabled.ant-pagination-next')) == 0):

      # 还能点击下一行
      driver.find_element(By.CSS_SELECTOR,
                           '.ant-pagination-next').click()
      time.sleep(5)
    else:
      break

  xw_toExcel(testData, '瑞昌市.xlsx')
  # Press the green button in the gutter to run the script.


if __name__ == '__main__':
  print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
